// pages/goods-list/index.js
var url = getApp().globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailData: '', //商品详情具体数据
    goods_storage: '',  //商品库存
    goods_price: '', //商品价格
    specALLArr: [],  //商品规格名称
    goods_list: [],
    propertyChildNames: '', //已选中的商品
    buyGoods_id: '', //购物车要传的商品id
    showView: false,
    num: 1,
    goods_img: '',
    showSure: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中，请稍后...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_type_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        gc_id: options.gc_id,
        curpage: 1
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading();
          var goodlists = res.data.datas;
          that.setData({
            goods_list: goodlists,
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      }
    });
    wx.setNavigationBarTitle({ title: options.gc_name})  
  },
  toScan: function() {
    wx.switchTab({
      url: '/pages/trace/index',
    })
  },
  /**
   * 切换规格选中状态
   * @author chelfinn
   * @date 2018-09-18
   */
  clickTap: function (e) {
    var that = this;
    var ids = [];   // 选中的id
    var valus = [];  // 选中商品的名字
    var specALLArr = that.data.specALLArr;
    var childs = that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData;
    // 取消该分类下的子栏目所有的选中状态
    for (var i = 0; i < childs.length; i++) {
      that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[i].active = false;
    }  
    // 设置当前选中状态
    that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[e.currentTarget.dataset.propertychildindex].active = true;
    that.setData({
      specALLArr: specALLArr
    });
    // 循环数组 获取点中状态时的规格
    for (var id in specALLArr) {
      for (var i in specALLArr[id].twoData) {
        if (specALLArr[id].twoData[i].active == true) {
          ids.push(specALLArr[id].twoData[i].id);  // 获取的商品选中时的id
          valus.push(specALLArr[id].twoData[i].name);   // 获取商品点中时的规格
        }
      };
    };
    var spec_id = ids.sort().join("|");   // 升序
    var spec_value = valus.toString().replace(/,/g, " ");  // 选中的规格
    var spec_list = that.data.detailData.spec_list;
    if (spec_value) {
      this.setData({
        propertyChildNames: spec_value,
      })
    }
    if (spec_id in spec_list) {
      that.setData({
        buyGoods_id: spec_list[spec_id], //获取购买的商品id
      });
      // 获取商品详情
      wx.request({
        url: url + '/mobile/index.php?act=goods&op=goods_detail',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        dataType: 'json',
        method: 'GET',
        data: {
          goods_id: that.data.buyGoods_id,
        },
        success: (res) => {
          if (res.data.code == 200) {
            var datas = res.data.datas;
            var specObj = res.data.datas.goods_info.spec_name;
            var tmp = {}; //商品规格
            var tmp2 = {}; //商品尺寸
            var specALLArr = []; // 商品贵和和商品
            for (var i in specObj) {
              tmp.id = i;
              tmp.name = specObj[i];
              tmp.twoData = [];
              for (var j in res.data.datas.goods_info.spec_value[i]) {
                tmp2.id = j;
                tmp2.name = res.data.datas.goods_info.spec_value[i][j];
                tmp2.propertyID = i;
                tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
              }
              specALLArr.push(JSON.parse(JSON.stringify(tmp)));
            };
            that.setData({
              detailData: datas,  //商品详情
              buyGoods_id: datas.goods_info.goods_id, //购买的商品价格
              goods_price: datas.goods_info.goods_price, //商品价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
              showView: true
            });
            if (that.data.goods_storage == 0) {
              this.setData({
                showSure: false
              });
            } else {
              that.setData({
                showSure: true
              })
            }; 
          };
          if (res.data.code == 400) {
            if (res.data.login == 0 && res.data.login) {
              wx.navigateTo({
                url: '/pages/authorize/index',
              })
            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none',
                duration: 1500,
                mask: true
              })
            };
          }
        },
        fail: () => {
          wx.showToast({
            title: '人太多啦',
            icon: 'none',
            duration: 2000
          })
        }
      });
    }
  },
  //点击减号
  minuAcvive: function () {
    var num = this.data.num;
    if (num > 1) {    //如果num大于1才能减
      num--;
    };
    // 将数值与状态写回
    this.setData({
      num: num,
    });
  },
  // 点击加号 
  addActive: function () {
    var num = this.data.num;
    num++;
    // 将数值与状态写回
    this.setData({
      num: num,
    });
  },
  /**
   * 输入框事件
   */
  bindManual: function (e) {
    var num = e.detail.value;
    // 将数值与状态写回
    this.setData({
      num: num
    });
  },
  // 加入购物车--展开弹窗
  addToCar: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var img = e.currentTarget.dataset.goods_img;
    var mobile = wx.getStorageSync("mobile");
    if (!mobile) {
      wx.navigateTo({
        url: '/pages/phone/index',
      })
    };
    this.setData({
      goods_img: img,
    })    
    that.getDetails(dataset);
  },
  /**
   * 获取商品详情
   */
  getDetails: function (dataset){
    var that = this;
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: dataset.goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          var goods_spec = [];
          var spec_id = [];
          for (var spec_d in res.data.datas.goods_info.goods_spec) {
            goods_spec.push(res.data.datas.goods_info.goods_spec[spec_d]);  // 商品规格
            spec_id.push(spec_d);
            var spec = goods_spec.toString().replace(/,/g, " ");
          };
          for (var i in specObj) {  
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];          
            for (var j in res.data.datas.goods_info.spec_value[i]){
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp2.active = (j in res.data.datas.goods_info.goods_spec) ? true : false;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));    
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (spec) {
            this.setData({
              propertyChildNames: spec,
            })
          };
          that.setData({
            specALLArr: specALLArr, 
            detailData: datas,  //商品详情
            buyGoods_id: dataset.goods_id, //购买的商品价格
            goods_price: dataset.goods_price, //商品价格
            goods_storage: dataset.goods_storage, //商品库存
            showView: true
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000,
        })
      }
    });
  },
  /**
   * 加入购物车--提交购买
   * @author chelfinn
   * @date 2018-09-19
   */

  addInCar: function (e){
    var that = this;
    var name = this.data.propertyChildNames.split(" ");
    if (this.data.specALLArr.length == 0) {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
    } else {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
      if (name.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格和尺寸~',
          showCancel: false,
        });
        return false;
      }
    }
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_add',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'POST',
      data: {
        key: wx.getStorageSync('key'),
        goods_id: e.currentTarget.dataset.goods_id,
        quantity: e.currentTarget.dataset.quantity
      },
      success: (res)=>{
        if(res.data.code == 200){
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          });
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        }else{
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
      num: 1
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 跳转到商品详情页
   */
  toGoodsDetailsTap: (e) => {
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + e.currentTarget.dataset.goods_id,
    });
  }
})